package com.nonobank.config.spring;

import java.util.Iterator;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nonobank.config.IConfigManager;

public class ZooKeeperPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{

	private static final String SERVER_NAME = "server.name";
	
	private static final String EVN_NAME = "server.evn";
	
	private IConfigManager configManager;
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
	
		String serverName = props.getProperty(SERVER_NAME);	
		String envName = props.getProperty(EVN_NAME);
		
		fillConfigs(props, serverName, envName);
		
		super.processProperties(beanFactoryToProcess, props);
	}

	/**
	 * 从配置管理中心获取数据，填充Props
	 * @param props
	 * @param serverName
	 * @param envName
	 */
	private void fillConfigs(Properties props, String serverName, String envName) {
		String json = configManager.getValue(serverName, envName);
		if(!StringUtils.isEmpty(json)){
			JSONObject jsonObject = (JSONObject) JSON.parse(json);
			Iterator<String> iterator = jsonObject.keySet().iterator();
			while(iterator.hasNext()){
				String key = iterator.next();
				String value = jsonObject.getString(key);
				props.put(key, value);
			}
		}
	}

	public void setConfigManager(IConfigManager configManager){
		this.configManager = configManager;
	}
	
}
